import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Input, Drawer, Tag, Space } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateUserForm from './components/CreateForm';
import UpdateUserForm from './components/UpdateForm';
import { getList, queryRule, updateRule, addRule, removeRule } from './service';
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule({
      name: fields.name,
      desc: fields.desc,
      key: fields.key,
    });
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule({
      key: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const UsersList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  
const columns = [
  // {
  //   title: '标识',
  //   dataIndex: 'id',
  //   key: 'id',
  // },
  {
    title: '用户名',
    width: 150,
    dataIndex: 'username',
    // 固定列在左侧
    fixed: 'left', 
    key: 'username',
    tip: '用户名是用户的标识，并且是唯一的。',
    render: (dom, entity) => {
      return <a onClick={() => setRow(entity)}>{dom}</a>;
    },
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
    // key: 'nickname',
  },
  {
    title: '性别',
    dataIndex: 'gender',
    // key: 'gender',
    width: 50,
    valueEnum: {
      0: {
        text: '女'
      },
      1: {
        text: '男'
      }
    }
  },
  {
    title: '密码',
    dataIndex: 'password',
    // key: 'password',
  },
  {
    title: '用户状态',
    dataIndex: 'status',
    valueEnum: {
        0: {
            text: '已禁用',
            status: 'Error',
        },
        1: {
            text: '正常用户',
            status: 'Success',
        },
        2: {
            text: '正在审批',
            status: 'Processing',
        },
        3: {
            text: '其他用户',
            status: 'Default',
        }
    }
  },
  {
    title: '余额',
    dataIndex: 'money',
    key: 'money',
    valueType: 'money',
  },
  {
    title: '创建时间',
    dataIndex: 'gmt_create',
    valueType: 'date',
    // key: 'gmt_create',
    sorter: (a, b) => {
      return a.gmt_create - b.gmt_create;
      // let aTimeString = a.gmt_create;
      // let bTimeString = b.gmt_create;
      // aTimeString = aTimeString.replace(/-/g, '/');
      // bTimeString = bTimeString.replace(/-/g, '/');
      // let aTime = new Date(aTimeString).getTime();
      // let bTime = new Date(bTimeString).getTime();
      // return bTime - aTime;
    }
  },
  {
    title: '修改时间',
    dataIndex: 'gmt_modified',
    valueType: 'dateTime',
    // key: 'gmt_modified',
  },
//   {
//     title: '部门',
//     dataIndex: 'dept_id',
//     // key: 'dept_id',
//     width: 50,
//   },
//   {
//     title: '删除标识',
//     dataIndex: 'deleted',
//     // key: 'deleted',
//     width: 50,
//   },
  // {
  //   title: '头像',
  //   dataIndex: 'avatar',
  // },
  // {
  //   title: '联系方式',
  //   dataIndex: 'mobile',
  // },
  // {
  //   title: '邮箱',
  //   dataIndex: 'email',
  // },
  {
    title: '年龄',
    dataIndex: 'age',
    sorter: (a, b) => a.age - b.age,
    width: 50,
  },
  {
    title: '身份证',
    dataIndex: 'id_card',
    render: id_card => (
      <>
        {id_card?.replace(/(\d{6})\d*(\d{4})/,'$1****$2')}
      </>
    ),
  },
  {
    title: "标签",
    dataIndex: "tags",
    render: tags => (
      <>
        {tags.map(tag => {
          let color = tag.length > 5 ? 'geekblue' : 'green';
          if (tag === 'loser') {
            color = 'volcano';
          }
          return (
            <Tag color={color} key={tag}>
              {tag.toUpperCase()}
            </Tag>
          );
        })}
      </>
    ),
  },
  {
    title: "操作",
    // 固定列在右侧
    fixed: 'right', 
    dataIndex: 'option',
    valueType: 'option',
    render: (_, record) => (
      <>
        <a
          onClick={() => {
            handleUpdateModalVisible(true);
            setStepFormValues(record);
            console.log(record);
            console.log(updateModalVisible);
          }}
        >
          修改
        </a>
        <Divider type="vertical" />
        <a href="">订阅警报</a>
      </>
    ),
  }
];
  return (
    <PageContainer>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="username"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params, sorter, filter) => getList({ ...params, sorter, filter })}

        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
        scroll={{
          scrollToFirstRowOnChange: true,// 当分页、排序、筛选变化后是否滚动到表格顶部
           x: 1500, 
        //    y: 800 
        }} // 列多则出现滚动条
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项&nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => (pre*100 + item.money*100)/100, 0)} 万
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <CreateUserForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable
          onSubmit={async (value) => {
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="key"
          type="form"
          columns={columns}
        />
      </CreateUserForm>
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateUserForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);

            if (success) {
              handleUpdateModalVisible(false);
              setStepFormValues({});

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.username && (
          <ProDescriptions
            column={2}
            title={row?.username}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.username,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default UsersList;
